<?php
namespace Admin\Common;

use Casbin\Enforcer;
use PhalApi\Exception\BadRequestException;

/**
 * 权限检测
 *  - 基于casbin的RBAC
 * @author dogstar 20201211
 */
class Rights {

    protected $enforcer;

    public function __construct() {
        // RBAC
        $this->enforcer = new Enforcer(API_ROOT . "/plugins/iadminos_rights_rbac_model.conf", $this->getPolicyCsvPath());
    }

    public function getPolicyCsvPath() {
        return API_ROOT . "/plugins/iadminos_rights_rbac_policy.csv";
    }

    public function check() {
        $di = \PhalApi\DI();
        $username = $di->admin->username;
        $object = $di->request->getServiceApi();
        $action = $di->request->getServiceAction();

        if ($this->enforcer->enforce($username, $object, $action) === true) {
                // permit
        } else {
                // deny the request, show an error
            throw new BadRequestException('权限不足');
        }
    }

    public function checkLite($username, $object, $action) {
        return $this->enforcer->enforce($username, $object, $action);
    }
}
